import { _ } from 'underscore';
import { ajax } from '../helper/helper.js';

function getUploadParam(callback) {
    ajax({
        type: 'GET',
        url: '/qiniu/operation/getQiniu',
        success: function (data) {
            data = JSON.parse(data);
            if (data.success) {
                callback(data.result.uptoken);
            } else {
                callback(false)
            }
        },
        error: function () {
            callback(false)
        }
    })
}
function uploadCDN(file, param, callback, progress) {
    var xhr = new XMLHttpRequest(),
        upload = xhr.upload;

    if (progress) {
        upload.addEventListener("progress", progress, false);
    }

    xhr.open("POST", 'https://up-z1.qbox.me', true);

    xhr.sendAsBinary(file, param);
    
    xhr.onload = function () {
        if (xhr.responseText) {
            callback(xhr.responseText)
        }
    };
}
function validFileType(type, typeList) {
    return _.contains(typeList, type)
}

XMLHttpRequest.prototype.sendAsBinary = function (file, param) {
    var formData = new FormData();

    formData.append('key', param.key);
    formData.append('token', param.token);
    formData.append('file', file);
    this.send(formData)
}

module.exports = {
    getUploadParam,
    validFileType,
    uploadCDN
}